package cn.flying.base.core.configuration;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import cn.flying.base.core.interceptor.AbstractRequestInterceptor;
import cn.flying.base.core.web.method.CustomHandlerMethodArgumentResolver;

/**
 * @description: web应用配置
 * @author: lvyong
 * @date: 2023年02月20日 18:32
 * @version: 1.0
 */
@Configuration
public class WebApplicationConfiguration implements WebMvcConfigurer {

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * Add Spring MVC lifecycle interceptors for pre- and post-processing of
     * controller method invocations and resource handler requests.
     * Interceptors can be registered to apply to all requests or be limited
     * to a subset of URL patterns.
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册自己的拦截器,并设置拦截的请求路径
        //addPathPatterns为拦截此请求路径的请求
        //excludePathPatterns为不拦截此路径的请求
        String[] exPath = {"/static/**", "/css/**", "/font/**", "/images/**", "/js/**", "/layui/**", "/lib/**", "/style/**", "/ztree/**", "/modules/**", "/adminui/**", "/config.js", "/captcha", "/login", "/doLogin", "/logout", "/forget", "/register", "/doRegister", "/auth/code", "/auth/valid/code", "/resetpass"};

        Map<String, AbstractRequestInterceptor> beans = applicationContext.getBeansOfType(AbstractRequestInterceptor.class);
        List<AbstractRequestInterceptor> list = beans.values().stream().sorted(Comparator.comparingInt(AbstractRequestInterceptor::getOrder)).collect(Collectors.toList());
        list.forEach(interceptor -> registry.addInterceptor(interceptor).addPathPatterns(new String[]{"/**"}).excludePathPatterns(exPath));
    }

    /**
     * Add handlers to serve static resources such as images, js, and, css
     * files from specific locations under web application root, the classpath,
     * and others.
     *
     * @param registry
     */
//    @Override
//    public void addResourceHandlers(ResourceHandlerRegistry registry) {
//        registry.hasMappingForPattern("");
//    }


    /**
     * 配置参数映射
     * @param argumentResolvers
     */
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new CustomHandlerMethodArgumentResolver());
    }
}
